//
//  WatchfaceFileDownloader.m
//  uteped_sdk
//
//  Created by mateng on 2024/5/9.
//

#import "WatchfaceFileDownloader.h"
  
@implementation WatchfaceFileDownloader {
    NSURLSession *_session;
    NSURLSessionDownloadTask *_downloadTask;
    void (^_progressHandler)(float);
    void (^_completionHandler)(NSURL *, NSError *);
}
  
- (void)startDownloadWithURL:(NSURL *)url toFileName:(NSString *)fileName progressHandler:(void (^)(float progress))progressHandler completionHandler:(void (^)(NSURL *fileURL, NSError *error))completionHandler {
    // 配置 URLSession
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    _session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
      
    // 创建一个下载任务
    _downloadTask = [_session downloadTaskWithURL:url];
      
    // 存储回调闭包以便后续使用
    _progressHandler = progressHandler;
    _completionHandler = completionHandler;
      
    // 开始下载任务
    [_downloadTask resume];
}
  
#pragma mark - NSURLSessionDownloadDelegate
  
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSError *error = nil;
    NSURL *documentsDirectory = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask][0];
    NSURL *destinationURL = [documentsDirectory URLByAppendingPathComponent:downloadTask.response.suggestedFilename];
      
    if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:destinationURL error:&error]) {
        NSLog(@"Error moving file: %@", error);
        _completionHandler(nil, error);
    } else {
        NSLog(@"File saved at path: %@", destinationURL.path);
        _completionHandler(destinationURL, nil);
    }
}
  
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    if (error) {
        NSLog(@"Download task finished with error: %@", error);
    } else {
        NSLog(@"Download task finished successfully");
    }
      
    // 清理
    [_session invalidateAndCancel];
    _session = nil;
    _downloadTask = nil;
}
  
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    if (totalBytesExpectedToWrite > 0) {
        float progress = (float)totalBytesWritten / (float)totalBytesExpectedToWrite;
        _progressHandler(progress);
    }
}
  
@end
